package com.nexgo.payment.trans;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.nexgo.common.ByteUtils;
import com.nexgo.data.entity.RecvData;
import com.nexgo.data.entity.mapper.EntityDataMapper;
import com.nexgo.data.json.JsonRecData;
import com.nexgo.data.json.JsonSendData;
import com.nexgo.data.json.JsonTools;
import com.nexgo.data.json.bean.JsonBody;
import com.nexgo.payment.App;
import com.nexgo.payment.BaseTransView;
import com.nexgo.payment.R;
import com.nexgo.payment.action.ActionResult;
import com.nexgo.payment.action.ActionStep;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.ResponseState;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.entity.MessageData;
import com.nexgo.payment.util.ByteUtil;
import com.nexgo.payment.util.MessageHelper;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.util.TransUtils;
import com.nexgo.payment.util.BassInfoUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 适用于与后台交互的无卡交易
 *
 * Created by xiaox on 2017/9/12.
 */
public abstract class AbsOnlinePresenter extends AbsBaseTransPresenter {
    private final Logger mLog = LoggerFactory.getLogger(AbsOnlinePresenter.class.getSimpleName());

    //是否首次进入标识
    private boolean mIsFirstTime = true;



    protected AbsOnlinePresenter(@NonNull BaseTransView view, @NonNull DataSource repository) {
        super(view, repository);
    }

    /**
     * 第一个发起的action
     *
     */
    protected abstract void onFirstAction();

    /**
     * 所有成功交易最后一步
     *
     * @param recvData 响应数据
     */
    protected abstract void onTransSuccess(RecvData recvData);

    @Override
    public void start() {
        super.start();
        if (mIsFirstTime) {
            onFirstAction();
            mIsFirstTime = false;
        }
    }

    @Override
    public void importActionResult(ActionResult actionResult) {
        Object data = actionResult.getData();
        ActionStep step = (ActionStep) actionResult.getAction().getActionStep();
        int ret = actionResult.getRet();
        mLog.debug("curr action step {} ret {}", step, actionResult.getRet());
        //统一失败处理
        if (ret != ActionResult.SUCC) {
            onlineNext(false, data);
        } else {
            //成功处理
            onlineNext(true, data);
        }
    }



    /**
     * 联机请求完下一步动作
     *
     * @param isConnected 是否已与后台交互
     * @param data
     */
    protected void onlineNext(boolean isConnected, Object data) {
        if(null==data){
           return;
        }
        //isConnected为false，说明无网络，此时未存包
        MessageData messageData = (MessageData) data;
        mLog.debug("RecvBodyData = {}", messageData.getJsonRecData().getREQ_BODY().toString());
        if (!isConnected) {
            postMainThread(() -> mView.showConnectFailed());
        } else {
            if (messageData == null) {
                //超时或接收失败等
                postMainThread(() -> mView.showTransFailed());
                return;
            }
            JsonRecData jsonRecData = messageData.getJsonRecData();
            JsonSendData jsonSendData = messageData.getJsonSendData();

            //第二层响应码判断
            if(jsonRecData.getREQ_BODY() == null) {
                postMainThread(() -> mView.showTransFailed());
                return;
            }
            if (!jsonRecData.getREQ_BODY().getResponseType().equals("N")) {
                String message=messageData.getJsonRecData().getREQ_BODY().getResponseMessage();
                String msg=messageData.getJsonRecData().getREQ_BODY().getResponseMsg();
                if (message != null) {
                    postMainThread(() -> mView.showError(message));
                } else if(msg != null){
                    postMainThread(() -> mView.showError(msg));
                }else {
                    postMainThread(() -> mView.showError(App.sContext.getString(R.string.trans_err)));
                }
                return;
            }

            if(mTransData.getTransType().equals(TransType.RESET_GPS)){
                onTransSuccess(null);
                return;
            }else if(mTransData.getTransType().equals(TransType.WORK_MASTER_KEY_DOWN)){
                RecvData recvData=new RecvData();
                recvData.setJsonRecData(jsonRecData);
                onTransSuccess(recvData);
                return;
            }

            //解密加密Decrypt
            String str = jsonRecData.getREQ_BODY().getDECRYPT();
            mLog.debug("加密Decrypt = {}",str);
            try {
                //xhj add
//                String str1 = UnionApi.getInstance().DecryptData(2, jsonSendData.getREQ_HEAD().getTranscode(),
//                        jsonSendData.getREQ_HEAD().getMcht_id(),jsonSendData.getREQ_HEAD().getTerm_trans_time(), str);
                String str1 =ByteUtil.CalcByWKey(str,true);
                mLog.debug("解密Decrypt = {}",str1);
                jsonRecData.getREQ_BODY().setDECRYPT("{"+str1+"}");//解密出来的数据前后补{}
                JsonBody jsonBody = JsonTools.fromJson( jsonRecData.getREQ_BODY().getDECRYPT(),JsonBody.class);
                if(jsonBody.get_$8583data() == null){
                    postMainThread(() -> mView.showTransFailed());
                    return;
                }
                byte[] recv8583Data = ByteUtils.commonString2Bcd(jsonBody.get_$8583data());
                mLog.debug("接收的8583 = {}", ByteUtils.byteArray2HexString(recv8583Data));
                //解8583包
                if(recv8583Data != null) {
                    final EntityDataMapper mapper = new EntityDataMapper();
                    RecvData recvData = mapper.rTransform(recv8583Data);

                    String keyData = new String();
                    if(jsonBody.getPin_key() != null){
                        keyData = keyData + jsonBody.getPin_key();
                    }
                    if(jsonBody.getPin_key_check() != null){
                        keyData = keyData + jsonBody.getPin_key_check();
                    }
                    if(jsonBody.getMac_key() != null){
                        keyData = keyData + jsonBody.getMac_key();
                    }
                    if(jsonBody.getMac_key_check() != null){
                        keyData = keyData + jsonBody.getMac_key_check();
                    }
                    if(jsonBody.getData_key() != null){
                        keyData = keyData + jsonBody.getData_key();
                    }
                    if(jsonBody.getData_key_check() != null){
                        keyData = keyData + jsonBody.getData_key_check();
                    }
                    if(keyData != null) {
                        recvData.setAdditionalRespData(keyData);
                    }
                    messageData.setRecvData(recvData);
                }
            } catch (Exception e) {
                mLog.debug("处理接收数据失败");
                postMainThread(() -> mView.showTransFailed());
                e.printStackTrace();
                return;
            }

            int keyIdx = Integer.parseInt(StringUtils.firstNonEmpty(mRepository.getParamValue(PreferencesConstants.MASTER_KEY_INDEX), "0"));
            ResponseState responseState = MessageHelper.checkResponse(messageData.getSendData(), messageData.getRecvData(), keyIdx);
            switch (responseState) {
                case SUCCESS:
                    onTransSuccess(messageData.getRecvData());
                    break;
                case ERR_RESPONSE:
                    //A0特殊处理
                    if (TransUtils.isNeedReLogin(messageData.getRecvData().getRespCode())) {
                        mLog.debug("后台校验mac错");
                        mRepository.setParamValue(PreferencesConstants.IS_NEED_LOGIN, "1");
                        mRepository.syncParamValue();
                    }
                    postMainThread(() -> showRespCodeError(messageData.getRecvData().getRespCode()));
                    break;
                default:
                    postMainThread(() -> mView.showTransFailed());
                    break;
            }
        }
    }

    /**
     * 显示响应码错误时的提示信息
     *
     * @param respCode
     */
    void showRespCodeError(String respCode) {
        //lr add
        if(TextUtils.isEmpty(respCode)){
            respCode = App.sContext.getString(R.string.trans_fail);
        }

        String errTip = App.sContext.getString(R.string.response_code, respCode)
                + "\n"
                + MessageHelper.getResponseCodeErrorInfo(respCode);

        postMainThread(() -> mView.showError(errTip));
    }

    @Override
    public boolean checkloctionIsNull() {
        //判断经纬度
        if("0.0".equals(mRepository.getParamValue(PreferencesConstants.LATITUDE))||"0.0".equals(mRepository.getParamValue(PreferencesConstants.LONGITUDE))){
            if(! BassInfoUtil.checkBaseInfo(App.sContext)){
                return true;
            }
            return false;
        }
        return false;
    }
}
